{% set entry_types = ['open', 'close', 'transaction', 'balance', 'note', 'document', 'pad', 'query', 'custom'] %}
{% set sub_types = {
  'custom': (
    ('budget', 'B', _('Budget entries')),
  ),
  'document': (
    ('discovered', 'D', _('Documents with a #discovered tag')),
    ('linked', 'L', _('Documents with a #linked tag')),
  ),
  'transaction': (
    ('cleared', '*', _('Cleared transactions')),
    ('pending', '!', _('Pending transactions')),
    ('other', 'x', _('Other transactions')),
  ),
} %}
{% set keyboard_shortcuts = {
  'open': 's o',
  'close': 's c',
  'balance': 's b',
  'note': 's n',
  'pad': 's p',
  'query': 's q',
  'custom': 's C',
  'budget': 's B',

  'transaction': 's t',
  'cleared': 't c',
  'pending': 't p',
  'other': 't o',

  'document': 's d',
  'discovered': 'd d',
  'linked': 'd l',
} %}
{% set short_type = {
   'balance': 'Bal',
   'close': 'Close',
   'document': 'Doc',
   'note': 'Note',
   'open': 'Open',
} %}
{% if not request.args.get('show') %}
{% set journal_show = g.ledger.fava_options['journal-show'] + g.ledger.fava_options['journal-show-transaction'] + g.ledger.fava_options['journal-show-document'] %}
{% else %}
{% set journal_show = request.args.getlist('show') %}
{% endif %}

{% macro account_link(name) %}<a class="account-link" href="{{ url_for('account', name=name) }}">{{ name }}</a>{% endmacro %}
{% macro render_metadata(metadata, entry_hash=None) -%}
{% if metadata %}
<dl class="metadata">
  {% for key, value in metadata.items() %}
  <dt>{{ key }}:</dt>
  <dd>
  {%- if key.startswith('document') %}<a class="filename" data-remote target=_blank href="{{ url_for('statement', entry_hash=entry_hash, key=key) }}">{{ value }}</a>
  {% elif value is string and (value.startswith('http://') or value.startswith('https://')) %}<a class="url" data-remote target=_blank href="{{ value }}">{{ value }}</a>
  {% else %}
    {{ value }}
  {% endif -%}
    {%- if key.startswith('document') %}</a>{% endif -%}
  </dd>
  {% endfor %}
</dl>
{% endif %}
{%- endmacro %}
{% macro render_tags_links(entry) -%}
{% for tag in entry.tags|sort %}<span class="tag">#{{ tag }}</span>{% endfor %}
{% for link_ in entry.links|sort %}<span class="link">^{{ link_ }}</span>{% endfor %}
{%- endmacro %}

{% macro journal_table(entries, show_change_and_balance=False) %}
{% autoescape false %}
<form id="entry-filters" class="wide-form">
  <span class="spacer"></span>
  {% for type in entry_types %}
  <button type="button" title="Toggle {{ type|capitalize }} entries" data-type="{{ type }}" data-key="{{ keyboard_shortcuts[type] }}"{% if type not in journal_show %} class="inactive"{% endif %}>{{ type|capitalize }}</button>
  {% if type in sub_types.keys() %}
  {% for sub_type in sub_types[type] %}
  <button type="button" title="{{ sub_type.2 }}" data-type="{{ sub_type.0 }}" data-key="{{ keyboard_shortcuts[sub_type.0] }}" class="small {{ type }}-toggle{% if sub_type.0 not in journal_show or type not in journal_show %} inactive{% endif %}">{{ sub_type.1 }}</button>
  {% endfor %}
  {% endif %}
  {% endfor %}
  <button type="button" title="Toggle metadata" data-type="metadata" data-key="m"{% if 'metadata' not in journal_show %} class="inactive"{% endif %}>{{ _('Metadata') }}</button>
  <button type="button" title="Toggle postings" data-type="postings" data-key="p"{% if 'postings' not in journal_show %} class="inactive"{% endif %}>{{ _('Postings') }}</button>
</form>
<ol class="flex-table journal{% for type in journal_show %} show-{{ type }}{% endfor %}">
    <li class="head">
        <p>
        <span class="datecell" data-sort="num" data-order="desc">{{ _('Date') }}</span>
        <span class="flag" data-sort="string">{{ _('F') }}</span>
        <span class="description" data-sort="string">{{ _('Narration/Payee') }}</span>
        <span class="num">{{ _('Position') }}</span>
        <span class="num">{{ _('Price') }}</span>
        <span class="num">{{ _('Cost') }}</span>
        {% if show_change_and_balance %}
        <span class="num">{{ _('Change') }}</span>
        <span class="num">{{ _('Balance') }}</span>
        {% endif %}
        </p>
    </li>
{% for entry in entries|reverse %}
    {% if show_change_and_balance %}
        {% set entry, _, change, balance = entry %}
    {% endif %}
    {% set type = entry.__class__.__name__.lower() %}
    {% set entry_hash = entry|hash_entry %}
    {% set metadata = entry.meta|remove_keys(['__tolerances__', '__automatic__', 'filename', 'lineno']) %}
    <li class="{{ type }} {{ entry.type or '' }} {{ entry.flag|flag_to_type if entry.flag else '' }}{{ ' linked' if entry.tags and 'linked' in entry.tags else '' }}{{ ' discovered' if entry.tags and 'discovered' in entry.tags else '' }}">
        <p>
        <span class="datecell" data-sort-value=-{{ loop.index }}><a href="#context-{{ entry_hash }}">{{ entry.date }}</a></span>
        <span class="flag">{% if type == 'transaction' %}{{ entry.flag }}{% else %}{{ short_type.get(type, type[:3]) }}{% endif %}</span>
        <span class="description{% if type != 'transaction' %}"{% else %} droptarget" data-entry="{{ entry_hash }}" data-entry-date="{{ entry.date }}" data-account-name="{{ entry.postings[0].account if entry.postings else "" }}"{% endif %}>
        {% if type == 'open' or type == 'close' %}
            {{ account_link(entry.account) }}
        {% elif type == 'note' %}
            {{ entry.comment }}
        {% elif type == 'query' %}
          <a href="{{ url_for('report', report_name='query', query_string='run "{}"'.format(entry.name)) }}">{{ entry.name }}</a>
        {% elif type == 'pad' %}
            {{ account_link(entry.account) }} from {{ account_link(entry.source_account) }}
        {% elif type == 'custom' %}
          <strong>{{ entry.type }}</strong>
          {%- for value in entry['values'] -%}
            &nbsp;{% if value.dtype|string == "<AccountDummy>" %}{{ account_link(value.value) }}
            {%- elif value.dtype|string == "<class 'beancount.core.amount.Amount'>" %}<span class="num">{{ value.value|format_amount }}</span>
            {%- elif value.dtype|string == "<class 'str'>" %}"{{ value.value }}"
            {%- elif value.dtype|string == "<class 'bool'>" %}{{ value.value }}
            {%- elif value.dtype|string == "<class 'datetime.date'>" %}{{ value.value }}{% endif -%}
          {%- endfor -%}
        {% elif type == 'document' %}
            {{ account_link(entry.account) }}
            <a class="filename" data-remote target=_blank href="{{ url_for('document', filename=entry.filename) }}">{{ entry.filename|basename }}</a>
            {{ render_tags_links(entry) }}
        {% elif type == 'balance' %}
            {{ account_link(entry.account) }}
            {% if entry.diff_amount %}
            <span class="spacer"></span>
            accumulated <span class="num">{{ (entry.amount.number + entry.diff_amount.number)|format_currency(entry.amount.currency, show_if_zero=True) }} {{ entry.amount.currency }}</span>
            {% endif %}
        {% elif type == 'transaction' %}
            <strong class="payee">{{ entry.payee or '' }}</strong>{% if entry.payee and entry.narration %}<span class="separator"></span> {% endif %}{{ entry.narration or '' }}
            {{ render_tags_links(entry) }}
        {% endif %}
        </span>
        <span class="indicators">
          {% for key, value in metadata.items() %}
          <span class="metadata-indicator" title="{{ key }}: {{ value }}">{{ key[:2] }}</span>
          {% endfor %}
          {% for posting in entry.postings %}
          <span{% if posting.flag %} class="{{ posting.flag|flag_to_type }}"{% endif %}></span>
          {% endfor %}
        </span>
        {% if type == 'balance' %}
          <span class="num bal {{ ' pending' if entry.diff_amount else '' }}">{{ entry.amount|format_amount }}</span>
        {% endif %}
        {% if show_change_and_balance %}
            <span class="change num">{% for pos in change|cost_or_value(entry.date) %}{{ pos.units|format_amount }}<br>{% endfor %}</span>
            <span class="num">{% for pos in balance|cost_or_value(entry.date) %}{{ pos.units|format_amount }}<br>{% endfor %}</span>
        </p>
        {% endif %}
        {{ render_metadata(metadata, entry_hash) }}
        {% if entry.postings %}
          <ul class="postings">
        {% for posting in entry.postings %}
        <li{% if posting.flag %} class="{{ posting.flag|flag_to_type }}"{% endif %}>
            <p>
                <span class="datecell"></span>
                <span class="flag">{{ posting.flag or '' }}</span>
                <span class="description droptarget" data-entry="{{ entry_hash }}" data-account-name="{{ posting.account }}" data-entry-date="{{ entry.date }}">{{ account_link(posting.account) }}</span>
                {# We want the output these amounts with the same precision as in the input file.
                   For computed values this might give a lot of digits, so format the price using the DisplayContext for now.#}
                <span class="num">{{ posting.units or '' }}</span>
                <span class="num">{{ posting.price|format_amount }}</span>
                <span class="num">{{ posting.cost.number }} {{ posting.cost.currency }}
                    {{- ', {}'.format(posting.cost.date) if posting.cost.date else '' }}
                    {{- ', "{}"'.format(posting.cost.label) if posting.cost.label else '' }}</span>
                {% if show_change_and_balance %}
                <span class="change num"></span>
                <span class="num"></span>
                {% endif %}
            </p>
            {{ render_metadata(posting.meta|remove_keys(['__automatic__', 'lineno', 'filename'])) }}
        </li>
        {% endfor %}
        </ul>
        {% endif %}
    </li>
{% endfor %}
</ol>
{% endautoescape %}
{%- endmacro %}
